package tool

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"time"
)

type Sign struct {
	Data SignData `json:"data"`
}

type SignData struct {
	Uid       int64  `json:"uid"`
	Account   string `json:"account"`
	LoginTime int64  `json:"login_time"`
}

const secret = "ce-second"

// GenerateSign 生成签名
func (si Sign) GenerateSign(t Sign) (s string, err error) {
	signJson, _ := json.Marshal(t)
	h := md5.New()
	h.Write([]byte(string(signJson) + secret))
	s = base64.StdEncoding.EncodeToString(signJson)
	s = s + fmt.Sprintf("%x", time.Now().Unix()%10)
	return
}

// CheckSign 检查签名
func (si Sign) CheckSign(sign string) (data Sign, err error) {
	sign = sign[:len(sign)-1]
	signJson, err := base64.StdEncoding.DecodeString(sign)
	if err != nil {
		return Sign{}, err
	}
	err = json.Unmarshal(signJson, &data)
	return
}

// ParseSign 解析签名
func (si Sign) ParseSign(s string) Sign {
	sign, _ := si.CheckSign(s)
	return sign
}
